package http_proxy_middleware

import (
	"fmt"
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"strings"
)

// HTTP IP 黑名单中间件
func HTTPBlackListModeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 获取IP白名单集合
		ipWhileList := []string{}
		if service.AccessControl.WhiteList != "" {
			ipWhileList = strings.Split(service.AccessControl.WhiteList, ",")
		}
		// 获取IP黑名单集合
		ipBlackList := []string{}
		if service.AccessControl.BlackList != "" {
			ipBlackList = strings.Split(service.AccessControl.BlackList, ",")
		}
		// 判断是否开启权限校验
		if service.AccessControl.OpenAuth == 1 && len(ipWhileList) == 0 && len(ipBlackList) > 0 {
			if public.InStringsSlice(ipBlackList, c.ClientIP()) {
				middleware.ResponseError(c, 3000, errors.New(fmt.Sprintf("%s IP 没有权限访问", c.ClientIP())))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
